<template>
  <div class="translation-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link :to="`/english/weekTestExam?noticeId=${noticeId}&examPaperId=${examPaperId}`" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto"> 翻译</h5>
    </div>

    <!-- 翻译内容 -->
    <div class="translation-content">
      <div class="english-text">
        {{ currentTranslation.english }}
      </div>
      
      <div class="translation-input">
        <h6 class="mb-3">你的翻译：</h6>
        <textarea
          v-model="userTranslation"
          rows="6"
          class="form-control"
          placeholder="请输入你的中文翻译..."
        ></textarea>
      </div>
      
      <div class="translation-area" :class="{ show: showAnalysis }">
        <h6 class="mb-3">参考译文：</h6>
        <div class="reference-translation mb-4">
          {{ currentTranslation.chinese }}
        </div>

        <h6 class="mb-3">重点词汇：</h6>
        <ul class="mb-4">
          <li v-for="(word, index) in currentTranslation.keywords" :key="index">
            <span class="word-note" @click="showWordDetail(word)">{{ word.term }}</span> - {{ word.meaning }}
          </li>
        </ul>

        <h6 class="mb-3">句式分析：</h6>
        <div class="sentence-structure mb-4">
          <div v-for="(analysis, index) in currentTranslation.sentenceAnalysis" :key="index">
            {{ index + 1 }}. {{ analysis }}
          </div>
        </div>

        <h6 class="mb-3">翻译技巧：</h6>
        <div class="key-points">
          <div v-for="(tip, index) in currentTranslation.translationTips" :key="index">
            {{ index + 1 }}. {{ tip }}
          </div>
        </div>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="translation-tools">
      <div class="d-flex justify-content-center">
        <button 
          class="toggle-btn" 
          @click="checkTranslation"
        >
          <i class="bi bi-check-circle"></i> 提交答案
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import {moduleTypeDict, paperTypeDict} from "@/router/dict";
import http from "@/router/http";
import router from "@/router";

export default {
  name: 'TranslationView',
  data() {
    return {
      showAnalysis: false,
      noticeId: null,
      userTranslation: '',
      currentTranslation: {
        english: `The supermarket is designed to attract consumers. The moment you walk in, you are greeted by the sight and 
        smell of fresh flowers, bread and fruit—all items that appeal to the senses and make you feel good. 
        Supermarkets also play relaxing music, as research shows that this encourages shoppers to take their time, 
        and the longer people stay in a store, the more they are likely to spend.`,
        chinese: '超市的设计就是为了吸引消费者。一走进超市，映入眼帘的就是新鲜的花卉、面包和水果，闻到的也是这些物品的香味——这些都是诱人感官、令人愉悦的商品。超市还会播放轻松的音乐，因为研究表明这样能让购物者放慢脚步，而人们在商店停留的时间越长，消费的可能性就越大。',
        keywords: [
          { term: 'be greeted by', meaning: '映入眼帘；受到...的迎接' },
          { term: 'appeal to', meaning: '吸引；诱人' },
          { term: 'take their time', meaning: '放慢脚步；从容行事' }
        ],
        sentenceAnalysis: [
          'The moment you walk in... - 时间状语从句，表示"一...就..."',
          'the longer..., the more... - "越...越..."结构'
        ],
        translationTips: [
          '将被动语态"be designed to"转换为主动表达',
          '意译"appeal to the senses"为"诱人感官"',
          '将并列结构转化为汉语的递进关系'
        ]
      },
      selectYear: null,
      startTime: 0, // 记录答题开始时间（毫秒数）
      totalTimeSpent: 0, // 累计答题时间（毫秒数）
      subjectName: '',
      article: '',
      examPaperId: '',
      questionId: '',
      userAnswers: []
    }
  },
  mounted() {
    this.examPaperId = this.$route.query.examPaperId;
    this.noticeId = this.$route.query.noticeId;
    this.startTime = Date.now(); // 记录答题开始时间（毫秒数）
    this.fetchDataFromBackend();
  },
  methods: {
    toggleAnalysis() {
      this.showAnalysis = !this.showAnalysis
    },
    showWordDetail(word) {
      alert(`${word.term}: ${word.meaning}`)
    },
    checkTranslation() {
      this.showAnalysis = true
      this.submitAnswers();
    },
    async fetchDataFromBackend() {
      try {
        const moduleType = moduleTypeDict.find(item => item.code === 'fy').name;
        const params = {
          examPaperId: this.examPaperId,
          subjectName: 'english',
          moduleType: moduleType,
          currentQuestionIndex: 1
        }
        const response = await http.get('/student/question/getQuestionInfoForEnglish', {params: params});
        const data = response.data;
        if (data && data.code === 1 && data.response) {
          this.examPaperId = data.response.examPaperId;
          this.questionId = data.response.questionId;
          this.currentTranslation.english = data.response.article;
          this.subjectName = data.response.subjectName;
        } else {
          alert("暂无数据，请稍后再试");
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
        }
      } catch (error) {
        console.error('获取阅读数据失败:', error);
      }
    },
    async submitAnswers() {
      try {
        const currentTime = Date.now(); // 获取当前时间（毫秒数）
        this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        this.userAnswers.push({
          index: 0,
          value: this.userTranslation.trim(),
        })
        const submitParentData = {
          questionId: this.questionId,
          examPaperId: this.examPaperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 1,
          userAnswer: this.userAnswers,
          isTest: true
        }

        // 发送POST请求将答题数据提交到后端
        const response = await http.post('/student/answer/submitAnswerForEnglish', submitParentData);
        if (response.status === 200) {
          alert('答题数据提交成功');
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
          // 可以根据业务需求进行其他操作，比如提示用户提交成功，跳转到特定页面等
        } else {
          console.error('答题数据提交失败');
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
          // 同样可根据业务需求进行相应提示等操作
        }
      } catch (error) {
        console.error('提交答题数据出现错误:', error);
      }
    }
  }
}
</script>

<style scoped>
.translation-page {
  background-color: #f0f9f9;
  min-height: 100vh;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.translation-content {
  padding: 20px;
  background: white;
  margin: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.english-text {
  font-size: 1.1rem;
  line-height: 1.8;
  margin-bottom: 20px;
  color: #333;
  white-space: pre-line;
}

.translation-tools {
  position: sticky;
  bottom: 0;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

.translation-area {
  display: none;
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.translation-area.show {
  display: block;
}

.reference-translation {
  color: #28a745;
}

.key-points {
  color: #dc3545;
}

.word-note {
  color: #0066cc;
  cursor: pointer;
  text-decoration: underline dotted;
}

.sentence-structure {
  color: #6c757d;
  font-style: italic;
}

.toggle-btn {
  padding: 8px 20px;
  border-radius: 20px;
  margin: 0 5px;
  border: none;
  background: #f0f0f0;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.toggle-btn.active {
  background: #40e0d0;
  color: white;
}

.translation-input {
  margin: 20px 0;
}

.translation-input textarea {
  width: 100%;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1.1rem;
  line-height: 1.6;
  resize: vertical;
}

.translation-input textarea:focus {
  outline: none;
  border-color: #40e0d0;
  box-shadow: 0 0 0 2px rgba(64, 224, 208, 0.2);
}
</style> 